package com.linkhub.oms.component.excel.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.linkhub.oms.common.enums.IEnumConvert;
import com.linkhub.oms.component.excel.annotation.CellPropertyMapping;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.Objects;

/**
 * @Description: CellEnumIntegerConverter
 * @Author: echo
 * @Date: 2024/5/11 20:56
 * @Version: 1.0
 */
@Slf4j
public class CellEnumIntegerConverter implements Converter<Integer> {
    @Override
    public Class<?> supportJavaTypeKey() {
        return Integer.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    @SuppressWarnings("all")
    public Integer convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
                                     GlobalConfiguration globalConfiguration) throws Exception {
        String cellValue = cellData.getStringValue();
        Field field = contentProperty.getField();
        CellPropertyMapping mapping = field.getAnnotation(CellPropertyMapping.class);
        if (StringUtils.isBlank(cellValue) || Objects.isNull(mapping)) {
            return null;
        }

        ExcelCellEnumConvert<String, Integer> cellEnumConvert = (ExcelCellEnumConvert<String, Integer>)
                IEnumConvert.valueOf(cellValue, mapping.mappingEnum());
        if (Objects.isNull(cellEnumConvert)) {
            log.warn("【{}】列枚举值: 【{}】不符合转换规则", field.getName(), cellValue);
            return null;
        }

        return cellEnumConvert.getValue();
    }


}
